package com.ecotope.quartz.module.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ecotope.quartz.module.entity.AccessData;
import com.ecotope.quartz.module.opentsdb.ExpectResponse;
import com.ecotope.quartz.module.opentsdb.HttpClientImpl;
import com.ecotope.quartz.module.opentsdb.builder.MetricBuilder;
import com.ecotope.quartz.module.opentsdb.response.Response;
import com.ecotope.quartz.module.service.AccessDataService;
import com.ecotope.quartz.module.util.HttpURLConnectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @Author: TaiHuanChen
 * @Date: 2020/12/28 13:43
 */
@Slf4j
@Component
@EnableAsync
@EnableScheduling
@SuppressWarnings("all")
public class WaterEnvironmentSchedule {

    //省平台地址
    private String baseUrl = "http://59.202.42.88:8180/sjmh/dynamicservice/dynamicquery";
    //页大小
    private Integer pageSize = 10000;

    //页码
    private Integer pageNum = 1;

    private String fwxhYys = "4852dc97b4cb4ab9a89c88dce992f36c";
    private String keyYys = "91029da2-2f0d-41a5-8c94-845cfef3da7b";

    String fwxhDbs = "5048f9185ec34d338386ffce2613a1cd";
    String keyDbs = "adf6ba7e-78be-487e-b285-9cb2e9f14a5c";

    @Autowired
    private AccessDataService accessDataService;

    /**
     * 饮用水每日
     */
    @Scheduled(cron = "0 36 * * * ?")
    @Async
    public void getYYSXSDateAndInsertOpentsdb() {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //当前日期前1天
        calendar.add(Calendar.HOUR, -3);
        date = calendar.getTime();
        String KSSJ = df.format(date);

        Date dateNew = new Date();
        String JSSJ = df.format(dateNew);

        HttpClientImpl client = new HttpClientImpl("http://61.164.218.155:61242");
        //饮用水质监测请求地址——省平台
        try {
            String kssj = URLEncoder.encode(KSSJ, "utf-8");
            String jssj = URLEncoder.encode(JSSJ, "utf-8");
            String url = baseUrl + "?fwxh=" + fwxhYys + "&key=" + keyYys + "&pagenum=" + pageNum + "&pageSize=" + pageSize + "&KSSJ=" + kssj + "&JSSJ=" + jssj;
            String methodReturn = HttpURLConnectionUtil.getMethod(url);
            if (HttpURLConnectionUtil.isJsonObject(methodReturn)) {
                JSONObject jsonObject = JSONObject.parseObject(methodReturn);
                JSONObject data = jsonObject.getJSONObject("data");
                String yyszdjcxssj = data.getString("YYSZDJCXSSJ");
                if (yyszdjcxssj != null && !"[]".equals(yyszdjcxssj)) {
                    //mysql数据库 记录数据插入时间
                    AccessData accessData = AccessData.builder().type(10).url("小时数据===>" + KSSJ + "--" + JSSJ).data("饮用水").build();
                    accessDataService.insert(accessData);
                    //插入opentsdb
                    JSONArray jsonArray = JSONArray.parseArray(yyszdjcxssj);
                    for (Object o : jsonArray) {
                        Map map = JSONObject.parseObject(o.toString(), Map.class);
                        String jcz = (String) map.get("JCZ");
                        String jcsj = (String) map.get("JCSJ");
                        String host = (String) map.get("CDBH");
                        String sjbj = (String) map.get("SJBJ");
                        if (sjbj != null && "正常".equals(sjbj)) {
                            sjbj = "1";
                        } else {
                            sjbj = "0";
                        }
                        String yzbh = (String) map.get("YZBH");
                        if (yzbh == null && yzbh == "") {
                            yzbh = "0";
                        }
                        //转换时间戳
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        if (jcsj != null) {
                            long timestamp = sdf.parse((jcsj)).getTime();
                            map.remove("JCSJ");
                            MetricBuilder builder = MetricBuilder.getInstance();
                            for (Object entry : map.entrySet()) {
                                Map.Entry<String, Object> map1 = (Map.Entry<String, Object>) entry;
                                double value = 0.0;
                                if (jcz != null && jcz != "") {
                                    value = Double.parseDouble(jcz);
                                }
                                builder.addMetric("mete.drinkingWater").setDataPoint(timestamp, value).addTag("host", host)
                                        .addTag("index", yzbh).addTag("SJBJ", sjbj);
                            }
                            //存入opentsdb
                            Response response = client.pushMetrics(builder,
                                    ExpectResponse.SUMMARY);
                            if (!response.isSuccess()) {
                                log.info(response.getErrorDetail().toString());
                            }
                        }
                    }
                } else {
                    //mysql数据库 记录数据插入时间
                    AccessData accessData = AccessData.builder().type(10).url("返回数据为空" + KSSJ + "--" + JSSJ).data("饮用水").build();
                    accessDataService.insert(accessData);
                    log.info("返回数据为空");
                }
            } else {
                log.info(methodReturn);
                //mysql数据库 记录数据插入时间
                AccessData accessData = AccessData.builder().type(10).url(methodReturn + KSSJ + "--" + JSSJ).data("饮用水").build();
                accessDataService.insert(accessData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    /**
     * 地表水每日
     */
    @Scheduled(cron = "0 42 * * * ?")
    @Async
    public void getDBSXSDateAndInsertOpentsdb() {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //当前日期前1天
        calendar.add(Calendar.HOUR, -3);
        date = calendar.getTime();
        String KSSJ = df.format(date);

        Date dateNew = new Date();
        String JSSJ = df.format(dateNew);

        HttpClientImpl client = new HttpClientImpl("http://61.164.218.155:61242");
        try {
            String kssj = URLEncoder.encode(KSSJ, "utf-8");
            String jssj = URLEncoder.encode(JSSJ, "utf-8");
            String url = baseUrl + "?fwxh=" + fwxhDbs + "&key=" + keyDbs + "&pagenum=" + pageNum + "&pageSize=" + pageSize + "&KSSJ=" + kssj + "&JSSJ=" + jssj;
            String methodReturn = HttpURLConnectionUtil.getMethod(url);
            if (HttpURLConnectionUtil.isJsonObject(methodReturn)) {
                JSONObject jsonObject = JSONObject.parseObject(methodReturn);
                JSONObject data = jsonObject.getJSONObject("data");
                String szzdjcxssj = data.getString("SZZDJCXSSJ");
                if (szzdjcxssj != null && !"[]".equals(szzdjcxssj)) {
                    //mysql数据库 记录数据插入时间
                    AccessData accessData = AccessData.builder().type(12).url("小时数据===>" + KSSJ + "--" + JSSJ).data("地表水").build();
                    accessDataService.insert(accessData);
                    //插入opentsdb
                    JSONArray jsonArray = JSONArray.parseArray(szzdjcxssj);
                    for (Object o : jsonArray) {
                        Map map = JSONObject.parseObject(o.toString(), Map.class);
                        double value = 0.0;
                        if (map.get("JCZ") instanceof Integer) {
                            Integer Intjcz = (Integer) map.get("JCZ");
                            value = Intjcz;
                        } else {
                            BigDecimal Bigjcz = (BigDecimal) map.get("JCZ");
                            value = Bigjcz.doubleValue();
                        }
                        String jcsj = (String) map.get("JCSJ");
                        String host = (String) map.get("CDBH");
                        String sjbj = (String) map.get("SJBJ");
                        String yzbh = (String) map.get("YZBH");
                        if (sjbj != null && sjbj.equals("正常")) {
                            sjbj = "1";
                        } else {
                            sjbj = "0";
                        }
                        if (yzbh == null && yzbh == "") {
                            yzbh = "0";
                        }
                        //转换时间戳
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        if (jcsj != null) {
                            long timestamp = sdf.parse((jcsj)).getTime();
                            map.remove("JCSJ");
                            MetricBuilder builder = MetricBuilder.getInstance();
                            for (Object entry : map.entrySet()) {
                                Map.Entry<String, Object> map1 = (Map.Entry<String, Object>) entry;
                                builder.addMetric("mete.surfaceWater").setDataPoint(timestamp, value).addTag("host", host)
                                        .addTag("index", yzbh).addTag("SJBJ", sjbj);
                            }
                            //存入opentsdb
                            Response response = client.pushMetrics(builder,
                                    ExpectResponse.SUMMARY);
                            if (!response.isSuccess()) {
                                log.info(response.getErrorDetail().toString());
                            }
                        }
                    }
                    pageNum++;
                } else {
                    log.info("返回数据为空");
                    //mysql数据库 记录数据插入时间
                    AccessData accessData = AccessData.builder().type(12).url("返回数据为空" + KSSJ + "--" + JSSJ).data("地表水").build();
                    accessDataService.insert(accessData);
                }
            } else {
                log.info(methodReturn);
                //mysql数据库 记录数据插入时间
                AccessData accessData = AccessData.builder().type(12).url(methodReturn + KSSJ + "--" + JSSJ).data("地表水").build();
                accessDataService.insert(accessData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}



